//
//  RequestHandler.swift
//  
//
//  Created by 孙长坦 on 2022/4/21.
//

import Foundation
import WebKit
import RxSwift
import Logging

class RequestHandler: WebViewHandlerProtocol {

    static let id: String = "request"
    
    var logger = Logger(label: "LibUI.RequestHandler")
    
    private var disposeBag: DisposeBag = DisposeBag()
    
    init() {
        logger.logLevel = .debug
    }

    func handler(_ handler: WebViewHandlerProtocol,
                 webView: WKWebViewEx?,
                 frameInfo: WKFrameInfo,
                 params: [String: Any]?) {
        guard let webView = webView else {
            return
        }

        guard let params = params,
              let uuid = params["uuid"] as? String,
              let url = params["url"] as? String else {
            return
        }
        
        WebViewService
            .shared
            .request(baseUrl: params["baseUrl"] as? String,
                     url: url,
                     method: params["method"] as? String,
                     headers: params["headers"] as? [String: String],
                     params: params["params"] as? [String : Any],
                     data: params["data"])
            .subscribe { [weak self] result in
                self?.runSuccessCallback(webView: webView,
                                         uuid: uuid,
                                         code: 0,
                                         message: "request:ok",
                                         data: result,
                                         handlerParams: params)
            } onFailure: { [weak self] error in
                self?.runFailCallback(webView: webView,
                                      uuid: uuid,
                                      code: 1,
                                      message: error.localizedDescription,
                                      handlerParams: params)
            }
            .disposed(by: disposeBag)
    }
}
